import "./reset.css";
import dayjs from "dayjs";
//import roleForm from "../form/role.vue";
import editForm from "../form/index.vue";
import viewField from "../form/view.vue";
import editField from "../form/editField.vue";
//import { zxcvbn } from "@zxcvbn-ts/core";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
//import croppingUpload from "../upload.vue";
import { usePublicHooks } from "../../hooks";

import { addDialog, closeDialog } from "@/components/ReDialog";
import { type PaginationProps } from "@pureadmin/table";
import type {
  FormItemProps
  //RoleFormItemProps
} from "../utils/types";
import { getKeyList } from "@pureadmin/utils";
import {
  //getRoleIds,
  getTableClassList,
  getTableInfoList,
  saveForm,
  delFormByIDS,
  generateForm
  //getAllRoleList
} from "@/api/metaTable";
import {
  // ElForm,
  // ElInput,
  // ElFormItem,
  //ElProgress,
  ElMessageBox //,gitp
  //formItemProps
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  // watch,
  computed,
  reactive,
  onMounted
} from "vue";

export function useUser(tableRef: Ref, treeRef: Ref) {
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // 上传头像信息
  //const avatarInfo = ref();
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const higherDeptOptions = ref();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  //const viewField = ref();
  const viewFormRef = ref();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const form = reactive({
    // 左侧部门树的id
    deptId: 0,
    tableName: "",
    status: "",
    onePage: pagination,
    sortName: "id",
    sort: false
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "编号",
      prop: "id",
      width: 90,
      sortable: "custom"
    },
    {
      label: "源表名称",
      prop: "tableName",
      minWidth: 130,
      sortable: "custom"
    },
    {
      label: "是否生成源表",
      prop: "tableIsFaBu",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.tableIsFaBu === 0 ? "danger" : ""}
          effect="plain"
        >
          {row.tableIsFaBu === 0 ? "未生成" : "已生成"}
        </el-tag>
      )
    },
    {
      label: "机构代码",
      prop: "comID",
      width: 120,
      sortable: "custom"
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "addTime",
      formatter: ({ addTime }) => dayjs(addTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 300,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  //启用停用设置
  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.tableName
      }</strong>源表吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(async () => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          const Result = await saveForm(row);
          if (Result.isSuccess) {
            message("已成功修改用户状态", {
              type: "success"
            });
          } else {
            message(Result.msg, { type: "error" });
          }
        }, 300);
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  //修改设置
  function handleUpdate(row) {
    console.log(row);
  }

  //远程排序
  function sortChange({ column }) {
    form.sort = column.order == "ascending" ? true : false;
    form.sortName = column.property;
    onSearch();
  }

  function handleDelete(row) {
    message(`您删除了用户编号为${row.id}的这条数据`, { type: "success" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  //分页选择
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  async function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    const frmIDS = getKeyList(curSelected, "id");

    tableRef.value.getTableRef().clearSelection();
    const Result = await delFormByIDS({ ids: frmIDS });
    if (Result.isSuccess) {
      message(`已删除用户编号为 ${frmIDS} 的数据`, {
        type: "success"
      });
      onSearch();
    } else {
      message(Result.msg, { type: "error" });
    }
  }

  async function onSearch() {
    loading.value = true;
    const Result = await getTableInfoList(toRaw(form));

    if (Result.isSuccess) {
      dataList.value = Result.result;
      pagination.total = Result.onePage.total;
      pagination.pageSize = Result.onePage.pageSize;
      pagination.currentPage = Result.onePage.currentPage;
    } else {
      message(Result.msg, { type: "error" });
    }
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.deptId = 0;
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect({ id, selected }) {
    form.deptId = selected ? id : "";
    onSearch();
  }

  function formatHigherDeptOptions(treeList) {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].status === 0 ? true : false;
      formatHigherDeptOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }
  function openEditFieldDialog(row?: FormItemProps) {
    addDialog({
      title: `${row.tableName}源表`,
      props: {
        formInline: {
          id: row?.id ?? 0,
          tableName: row?.tableName ?? "",
          tableJson: row?.tableJson ?? "",
          tableIsFaBu: row?.tableIsFaBu ?? 0
        }
      },
      width: "80%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      center: true,
      alignCenter: true,
      footerRenderer: () => h({}, {}),
      contentRenderer: () => h(editField, { ref: ruleFormRef }),
      closeCallBack: ({ options }) => {
        //const dd = ruleFormRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        if (curData.tableIsFaBu == 0) {
          row.tableIsFaBu = 0;
        }
        //console.log(curData, "dd");
        //console.log(curData, "curData");
      }
    });
  }

  function openViewDialog(row?: FormItemProps) {
    addDialog({
      title: `${row.tableName}视图`,
      props: {
        formInline: {
          higherDeptOptions: formatHigherDeptOptions(higherDeptOptions.value),
          classID: row?.classID ?? 0,
          id: row?.id ?? 0,
          tableType: row?.tableType ?? 1,
          tableName: row?.tableName ?? "",
          tableJson: row?.tableJson ?? "",
          status: row?.status ?? 1,
          tableIsFaBu: row?.tableIsFaBu ?? 0,
          addUser: row?.addUser ?? 0,
          addTime: row?.addTime ?? "2023-8-9"
        }
      },
      width: "80%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      center: true,
      alignCenter: true,
      footerButtons: [
        {
          label: "保存",
          type: "primary",
          btnClick: () => {
            const dd = viewFormRef.value;
            dd.saveJson();
            onSearch(); // 刷新表格数据
          }
        },
        {
          label: "关闭",
          type: "success",
          btnClick: ({ dialog: { options, index } }) => {
            closeDialog(options, index);
          }
        }
      ],
      //footerRenderer: () => h({}, {}),
      contentRenderer: () => h(viewField, { ref: viewFormRef }),
      closeCallBack: () => {
        //const dd = ruleFormRef.value.getRef();
        // const curData = options.props.formInline as FormItemProps;
        //if (curData.tableIsFaBu == 0) {
        // row.tableIsFaBu = 0;
        // }
        //console.log(curData, "dd");
        //console.log(curData, "curData");
      }
    });
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}源表`,
      props: {
        formInline: {
          higherDeptOptions: formatHigherDeptOptions(higherDeptOptions.value),
          classID: row?.classID ?? 0,
          id: row?.id ?? 0,
          tableType: row?.tableType ?? 1,
          tableName: row?.tableName ?? "",
          tableJson: row?.tableJson ?? "",
          status: row?.status ?? 1,
          tableIsFaBu: row?.tableIsFaBu ?? 0,
          addUser: row?.addUser ?? 0,
          addTime: row?.addTime ?? "2023-8-9"
        }
      },
      width: "46%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了源表名称为${curData.tableName}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            const subResult = await saveForm(curData);
            if (subResult.isSuccess) {
              chores();
            } else {
              message(subResult.msg, { type: "error" });
            }
          }
        });
      }
    });
  }

  //根据JSON表单生成数据库实体
  async function generateFormToTable(row) {
    const Result = await generateForm({ id: row.id });
    if (Result.isSuccess) {
      row.tableIsFaBu = 1;
      message("操作成功！", { type: "success" });
    } else {
      message(Result.msg, { type: "error" });
    }
  }

  onMounted(async () => {
    treeLoading.value = true;

    // 归属部门
    const Result = await getTableClassList({ classType: 1 });
    const currentRS = Result.result;
    higherDeptOptions.value = handleTree(
      currentRS,
      currentRS["id"],
      currentRS["parentID"],
      currentRS["id"]
    );
    treeData.value = handleTree(
      currentRS,
      currentRS["id"],
      currentRS["parentID"],
      currentRS["id"]
    );
    treeLoading.value = false;
    await onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    sortChange,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    openEditFieldDialog,
    generateFormToTable,
    openViewDialog
  };
}
